<?php

namespace App\Admin\Controllers\Financial;

use App\Admin\Models\Financial\FinancialSubject;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\CommonExcelExport;
use Maatwebsite\Excel\Facades\Excel;
class FinancialSubjectController extends Controller
{

    public function getlist(Request $request)
    {
        $list = FinancialSubject::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function dopostadd(Request $request)
    {

        if(!$request->subject_name){
            return response()->json(['code' => '001', 'msg' => '科目名称不能为空']);
        }


        $moneylog_data = [
            'subject_name' => $request->subject_name,
            'create_at'=>time(),
            'update_at'=>time(),
            'remark'=>$request->remark ??''
        ];
        FinancialSubject::create($moneylog_data);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function dopostedit(Request $request)
    {
        $id=$request->id ?? 0;
        
        
        if(!$request->subject_name){
            return response()->json(['code' => '001', 'msg' => '科目名称不能为空']);
        }

        $one = FinancialSubject::where(['id'=>$id,'is_del'=>1])->first();
        if(!$one){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        FinancialSubject::where(['id'=>$id])->update(['subject_name'=>$request->subject_name,'remark'=>$request->remark ??'','update_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function dopostdel(Request $request)
    {
        $id=$request->id ?? 0;
        $one = FinancialSubject::where(['id'=>$id,'is_del'=>1])->first();
        if(!$one){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        FinancialSubject::where(['id'=>$id])->update(['is_del'=>2,'del_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }



    public function doexport(Request $request)
    {
        $list = FinancialSubject::getList($request)['list'];
        $exceldata = [];
        $row = [
            ['id'=>'科目管理'],
            [
                'id' => '序号',
                'subject_name' => '科目名称',
            ]
        ];
        foreach ($list as $key=>$val) {
            $exceldata[] = [
                
                'id' => $key+1,
                'subject_name' => $val['subject_name'],
            ];
        }

        $filename = '科目信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }
}